/*
 * Drunk Js
 * Author    :   Drunk
 * Website   :   http://drunkce.com,  http://idrunk.net
 */
var eg = { // means easyui grid
    market : {}, // grid对象集
    init : function(){
        if(!$e('.drunk-grid').length) return;
        eg.gridinit();
    },
    grid : function(c){ // 取grid对象
        if(!c) c = {selecter : '.drunk-grid'};
        if(!c.selecter) c.selecter = '.drunk-grid';
        if(!eg.market[c.selecter]) eg.market[c.selecter] = $e(c.selecter);
        return eg.market[c.selecter];
    },
    gridinit : function(){
        eg.grid();
        $e(window).bind('resize', eg.gridResize);
        $e('.easyui-panel').panel({onExpand : eg.gridResize, onCollapse : eg.gridResize});
        window.setTimeout(function(){$e(window).trigger('resize')}, 10);
    },
    gridResize : function(){
        var otherheight = $e('.panel:has(.calc-height)').outerHeight(true),
            winheight = $e(window).height(),
            counter = 0, heightRound;
        for(var i in eg.market) counter ++;
        heightRound = (winheight - otherheight) / counter; // 算出平均高度
        for(var i in eg.market) eg.market[i].datagrid('resize', {'height' : heightRound}); // 高度赋值
    },
    gridload : function(c, url){
        if(!eg.grid(c)) return; // location.reload();
        eg.grid(c).hasClass('easyui-treegrid') ?
            (url ? eg.grid(c).treegrid('load', url + '?druson=1') : eg.grid(c).treegrid('reload')) :
            (url ? eg.grid(c).datagrid('load', url + '?druson=1') : eg.grid(c).datagrid('reload'));
    },
    // 从表处理
    sb : function(line, data){ // means subordinate
        var c = {selecter : '.subordinate-main', data : data};
        if(!eg.grid(c).length || !(c.sb_urlmode = eg.grid(c).attr('data-subordinate-url').replace(/!main_id!/, data.id) + '?druson=1')) return null; // 如果无从表元素, 则不建从表
        eg.sbBuild(c);
    },
    sbBuild : function(c){
        var t = eg.grid(c);
        t[0].main_data = null; // 清空主表数据缓存
        if(t.css('display') != 'table') return t.datagrid('load', c.sb_urlmode);
        $.get(c.sb_urlmode, function(data){
            var tr = $('<tr>').appendTo($('<thead>').appendTo(t));
            t.attr('data-options', t.attr('data-options').replace(/\[pageSize\]/gi, data.pageSize)); // 更新pagesize
            for(var i in data.fields) $('<th data-options="'+data.fields[i].c+'">'+data.fields[i].field_name+'</th>').appendTo(tr);
            t.datagrid({'url' : c.sb_urlmode, 'onLoadSuccess' : function(){
                t[0].main_data = c.data; // 将主表数据缓存到从表
            }});
            eg.gridResize();
        });
    },

    // 通俗来讲就是新窗口打开
    ctrlExport : function(c, ids){
        ids = eg.getselected(c, 'id', ids);
        ids = $.isArray(ids) ? ids.join(',') : ids;
        if(!confirm('您确定要导出啊？')) return;
        if(!(c.status & 16) && (!ids || !ids.length)) return wuuye.dialog('请勾选 ' +c.name+ ' 的对象！', '提示');
        var url = location.href + (/\?/.test(location.href) ? '&' : '?') + 'druson=1&list_export=1&page=1';
        if(!(c.status & 16)) url += '&export_ids=' + ids;
        D.submit(url, 0, 1);
    },
    ctrlTab : function(c, ids){
        c.tabwin = 1;
        eg.ctrlIframe(c, ids);
    },
    ctrlIframe : function(c, ids){
        var url = c.urlmode;
        if(!$e.isPlainObject(c.config)) c.config = {};
        var tab = eg.grid(c); // 强制性交
        // 如果是有主表数据, 则尝试将主表ID记入iframe页面url
        if(tab[0] && tab[0].main_data) url = url.replace(/!id_main!/ig, tab[0].main_data['id']);
        if(!(c.status & 16)){ // &16 表添加
            var id = $.isArray(ids) && c.idsIsArray ? ids : eg.getselected(c, 0, ids);
            if(!id || !id.length) return wuuye.dialog('请勾选 ' +c.name+ ' 的对象！', '提示');
            if(id.length > 1 && c.status & 8) return wuuye.dialog('您仅能同时 ' +c.name+ ' 一个对象！', '提示');
            url = url.replace('!id!', id.join(','));
        }
        if($.isFunction(window[c.config.openpre]) && !c.openpreCalled){
            c.openpreCalled = 1;
            return window[c.config.openpre](c, ids);
        }
        c.tabwin ? window.top.wuuye.tabWin(url, c.title) : (c.config.dialog ? wuuye.dialog(url, c.title, c) : wuuye.window(url, c.title, c));
    },
    ctrlAjax : function(c, ids){
        var i = 0,
            handleChecked = c.status & 8,
            ids = eg.getselected(c, 'id', ids);
        eg.ajaxCounter = 0;
        if(handleChecked && (!ids || !ids.length)) return wuuye.dialog('请至少选择一个对象进行 ' +c.name+ ' 操作！', '提示');

        // 暴力插入
        if((c.status & 16) && $.isPlainObject(c.config) && c.config.callback){
            var callback; // 若状态&16且有配置回调函数, 则丢给回调函数处理之
            try{eval('callback = ' + c.config.callback);}catch(e){};
            if($.isFunction(callback)) return callback(c, ids);
        }

        if(handleChecked){
            if(confirm('您确定要 ' +c.name+ ' 选中的 ' +ids.length+ ' 个对象吗？')) for(; i<ids.length; i++) eg.ctrlAjaxing(c, c.urlmode.replace('!id!', ids[i]), ids);
        }else{
            if(confirm('您确定要 ' +c.name+ ' 所有筛选对象吗？')) eg.ctrlAjaxing(c, c.urlmode.replace('!id!', ids.join(',')), ids);
        }
    },
    ctrlAjaxing : function(c, url, ids){
        $e.get(url, function(data){
            if(!data || !data.status) return alert(data.info || data.message);
            if(!$.isArray(ids) || !ids.length || !(c.status & 8)){ // 如果不是批量操作
                wuuye.dialog(c.name+ '完成！', '提示：', {callback : function(){
                    eg.grid(c) ? eg.grid(c).datagrid('reload') : location.reload();
                }});
            }
            eg.ajaxCounter ++;
            if(eg.ajaxCounter >= ids.length){
                wuuye.dialog(c.name+ '完成！', '提示：');
                eg.grid(c) ? eg.grid(c).datagrid('reload') : location.reload();
            }
        }, 'json');
    },
    /**
     * 取选中的列表数据
     * @param c
     * @param field
     * @param ids
     * @returns {*}
     */
    getselected : function(c, field, ids){
        if($.isInt(ids)) ids = [ids];
        if($.isArray(ids)) return ids;
        field = field || 'id';
        var istree = !! eg.grid(c).treegrid,
            selected = istree ? eg.grid(c).treegrid('getSelections') : eg.grid(c).datagird('getSelections'),
            checked = istree ? 0 : eg.grid(c).datagird('getChecked');
        if(checked && checked.length) selected = checked;
        if(!selected || !selected.length) return '';
        if(field == '*') return selected;

        for(var i=0; i<selected.length; i++) selected[i] = selected[i][field];
        return selected;
    },
    // 数据处理, 将非grid格式化的数组格式化为如[rows:[], total:0]的形式
    gridata : function(data){
        if(!data) data = {};
        if(!data.rows) data.rows = [];
        if(!data.total) data.total = data.rows.length;
        return data;
    }
};

var wuuye = {
    c : {
        elem_draft : 'is_draft',
        istoper : window.top === window.self,
        win : {}
    },
    init : function(){
        if(typeof pageset !== 'undefined' && D.isPlainObject(pageset)) D.extend(wuuye.c, pageset); // 继承应入页面配置
        if(!(wuuye._tabs = $e('.body>.easyui-tabs')).length) return;
        wuuye.m = $e('.s-menu');
        wuuye.tab();
        $e(window).bind('resize', wuuye.adjust).trigger('resize');
    },
    tab : function(){
        var page_tag = wuuye.m.find('li>a');
        page_tag.bind('click', function(){
            var elem = $e(this),
                thref = elem.attr('href'),
                tname = elem.text();
            return wuuye.tabWin(thref, tname);
        });
        wuuye._tabs.tabs({
            onClose : function(title, index){
                wuuye.cache.tagsOpened.splice(index - 1, 1);
                wuuye.adjust();
            },
            onAdd : function(title, index){
                wuuye.adjust();
            }
        });
    },
    tabWin : function(thref, tname){
        var tcontent = '<iframe src="' +thref+ '"></iframe>',
            tagIndex = wuuye.cache.tagsOpened.search(thref, ['href']);

        if(tagIndex !== -1){
            wuuye._tabs.tabs('select', D.int(tagIndex) + 1);
            var ifr = wuuye._tabs.tabs('getSelected').find('iframe');
            if(ifr.length) ifr.attr('src', ifr.attr('src')); // 刷新新切换至的页面内容
        }else{
            wuuye._tabs.tabs('add', {title: tname, content: tcontent, closable: true});
            wuuye.cache.tagsOpened[wuuye.cache.tagsOpened.length] = {'href' : thref};
        }
        return false;
    },
    adjust : function(){
        window.setTimeout(function(){
            var bodyheight = wuuye._tabs.height(),
                tabhead = wuuye._tabs.find('.tabs-header'),
                tabbody = wuuye._tabs.find('.tabs-panels'),
                tabheadheight = tabhead.outerHeight(true);
            tabbody.height(bodyheight - tabheadheight);
        }, 200);
    },
    window : function(text, title, c, wname){
        if(!wname) wname = c.selecter || 'dwin'; // 若未定义窗口名, 则grid名即窗口名
        if(!$e.isPlainObject(c)) c = {};
        if(!$e.isPlainObject(c.config)) c.config = {};
        var isiframe, loadcalls = $e.Callbacks(),
            callbacks = $e.Callbacks(),
            closecalls = $e.Callbacks(),
            cancelcalls = $e.Callbacks();
        callbacks.add(function(){wuuye.winctrl(wname);});
        closecalls.add(function(){wuuye.winctrlbtn(wname, 2);});
        cancelcalls.add(function(){wuuye.winctrl(wname, 4);});
        if($e.isFunction(c.callback)) callbacks.add(c.callback);
        if($e.isFunction(c.closecall)) closecalls.add(c.closecall);
        if($e.isFunction(c.cancelcall)) cancelcalls.add(c.cancelcall);

        if(!wuuye[wname]){
            wuuye[wname] = $e('<div></div>').appendTo(document.body).dialog({
                iconCls: 'icon-edit',
                maximized: !D.int(c.config.width),
                width: c.config.width || 680,
                height: c.config.height || 500,
                collapsible : true,
                maximizable : true,
                resizable : true,
                closed: false,
                cache: false,
                modal: true,
                onClose: function(){closecalls.fire();},
                buttons: c.buttons ? c.buttons :
                    [{id : wuuye.names.idsave, text:'保存', iconCls:wuuye.names.iconsave, handler:function(){callbacks.fire();}}, {text:'取消', iconCls:'icon-cancel', handler:function(){cancelcalls.fire();}}]
            });
        }
        if(/^(?:https?:\/)?\//i.test(text)){
            isiframe = 1;
            text = '<iframe src="' +text+ '"></iframe>';
        }
        if(title) wuuye[wname].window('setTitle', title);
        if(text) wuuye[wname].html(text);
        wuuye[wname].window('open');
        if(isiframe){
            loadcalls.add(function(){wuuye.winctrl(wname, 8);});
            if($e.isFunction(c.loadcall)) loadcalls.add(c.loadcall);
            wuuye[wname].find('iframe').bind('load', function(){loadcalls.fire()});
        }
        wuuye.c[wname] = c;
    },
    dialog : function(text, title, c){
        if(!$.isPlainObject(c)) c = {callback : c};
        if(!$.isPlainObject(c.config)) c.config = {};
        var _dialog = '_dialog' + ((c.config.height || c.config.height) ? c.config.height +'x'+ c.config.height : '');
        if(!wuuye[_dialog]){
            wuuye[_dialog] = $e('<div></div>').appendTo(document.body).dialog({
                iconCls: 'icon-tip',
                maximized: !!c.config.max,
                width: c.config.width || 400,
                height: c.config.height || 200,
                collapsible : true,
                maximizable : true,
                resizable : true,
                closed: false,
                cache: false,
                modal: true,
                buttons : [{text:'确定', iconCls:'icon-ok', handler:function(){wuuye[_dialog].dialog('close');}}]
            });
        }
        if(!$.isFunction(c.callback)) c.callback = function(){};
        wuuye[_dialog].dialog({onClose:c.callback});
        if(/^(?:https?:\/)?\//i.test(text)) text = '<iframe src="' +text+ '"></iframe>'; // 扩展iframe支持
        wuuye[_dialog].html('<div class="wuuyedialog">' +text+ '</div>').dialog('setTitle', title).dialog('open').closest('.window').find('a.l-btn').trigger('focus');
    },
    savecall : function(data, wname){
        if(!wuuye.c[wname] || !$.isFunction(wuuye.c[wname].savecall)) return;
        wuuye.c[wname].savecall(data, wname);
    },
    handles : {
        task : function(){eg.ctrlTab({"title":"代办任务","status":16,"urlmode":"/index.php/base/task--1status%2611%2C10.html"});},
        overdue : function(){eg.ctrlTab({"title":"需滞纳金应收","status":16,"urlmode":"/index.php/base/receivable--1status%26256%2C256.html"});},
        receivable : function(){eg.ctrlTab({"title":"应收管理","status":16,"urlmode":"/index.php/base/receivable.html"});},
        checkout : function(){eg.ctrlTab({"title":"迁出客户","status":16,"urlmode":"/index.php/base/customer_tenant--1status%264%2C4.html"});},
        messageView : function(ids){eg.ctrlIframe({"title":"查看信息","status":17800,"urlmode":"/index.php/base/msg_view-!id!.html"}, ids);},
        messageIgnore : function(ids){eg.ctrlAjax({'name':'忽略',"status":16768,"urlmode":"/index.php/base/msg_ignore-!id!-druson~1.html"}, ids);}     
       
    },

    winctrl : function(wname, bit){
        if(bit & 4) return wuuye.winctrlbtn(wname, bit);
        var ifr = wuuye[wname].find('iframe');
        if(!ifr.length) return;
        var ifrForm = ifr[0].contentWindow.$('form.edit');
        if(ifrForm && ifrForm.length){
            ifrForm.attr(wuuye.names.win, wname);
            if(!(bit & 8)) return ifrForm.trigger('submit');
        }else if(ifrForm = ifr[0].contentWindow.$('.system-message')){
            ifrForm.attr(wuuye.names.win, wname);
        }
    },

    /**
     * 弹窗空间操作
     * @param wname string
     * @param bit int       {0:submit, 1:锁定提交按钮, 2:解锁提交按钮, 4:close}
     */
    winctrlbtn : function(wname, bit){
        if(!wname) return;
        var win = wuuye[wname], pwin = win.closest('.window');
        if(bit & 4) return win.window('close');
        if(bit & 3){
            var btn = pwin.find('#'+wuuye.names.idsave);
            if(!btn.length) return;
            bit & 1 ? btn.linkbutton({iconCls:wuuye.names.iconloading, text:wuuye.names.textloading}).linkbutton('disable').trigger('blur') :
                btn.linkbutton({iconCls:wuuye.names.iconsave, text:wuuye.names.textsave}).linkbutton('enable');
        }
    },

    /**
     * 窗口按钮操作, 设置按钮文案
     */
    winbtn : function(wname, btname, btntext){
        var win = wuuye[wname],
            pwin = win.closest('.window'),
            btn = pwin.find('#'+wuuye.names[btname]);
        btn.linkbutton({text:btntext});
    },

    /**
     * winbtn new (to create new button or return it)
     * @param wname
     * @param selecter
     * @param c object {html, align : 0=left/1=}
     */
    winbtnn : function(wname, selecter, c){
        var win = wuuye[wname].closest('.window'),
            btn = win.find(selecter);
        if(!btn.length && $e.isPlainObject(c)){
            var btnwrap = win.find('.dialog-button');
            btn = c.align ? $e(c.html).appendTo(btnwrap) : $e(c.html).prependTo(btnwrap);
            btn.linkbutton();
        }
        return btn;
    },

    formevent : function(){
        var f = $('form.edit'), pwin = window.parent, pwuuye = pwin.wuuye;
        f.bind('submit', function(){
            try{for(var ki=0; ki<variable.keditors.length; ki++) variable.keditors[ki].sync();}catch(e){}; // 双jQuery的引入解决了easyui与jqueryui的冲突却影响了kindeditor的自动同步, 故此手动同步
            f.find('[drunk-code=1]').val('').css('color', '#000'); // 如果空, 则置空
            wuuye.formonsubmit(function(){ // 能否提交咯
                wuuye.approval_selecter(function(){
                    var url = f.attr('action'),
                        wname = f.attr(wuuye.names.win);
                    data = f.serializeArray();
                    wuuye.hidden(wuuye.c.elem_draft, null, f);
                    $.ajax({
                        url : url,
                        data : data,
                        type : 'POST',
                        dataType : 'json',
                        beforeSend : function(){pwuuye.winctrlbtn(wname, 1);}, // 设置保存按钮为disabled状态
                        success : function(rs){wuuye.formsuccess(pwuuye, rs, wname, pwin);}
                    });
                });
            }, 1);
            return false;
        });
        wuuye.formapproval(f, pwuuye);
    },

    /**
     * 表单提交回调
     * @param callback  回调函数呗
     * @param bit int   {1 : 提交回调操作}
     * @returns {*}
     */
    formonsubmit : function(callback, bit){
        if(!wuuye.formcache) wuuye.formcache = {};
        if(!(bit & 1) && $.isFunction(callback)) return wuuye.formcache.submit = callback; // 如果有传入回调, 则记录回调函数
        if(!$.isFunction(wuuye.formcache.submit)) return callback.call(this);
        wuuye.formcache.submit.call(this, callback);
    },

    approval_selecter : function(callback){
        if(!$.isFunction(callback)) callback = $.noop(); // 若无回调, 则定义回调为一个空函数, 省得出错
        if(!wuuye.c.approval_selecter) return callback();

        var rsApp = wuuye.c.approval_selecter,
            items = rsApp.processes.items,
            div = '<div style="width:360px;margin:20px auto;line-height:30px;text-align:center;"><table class="approval-selecter" style="width:100%;">' +
                '<tr><th colspan="2" style="color:#999;font-size:14px;font-weight:400;text-align:center;"><span style="color:#000;">您的信息需要审批，</span>请选择相应的审批者：</th></tr>' +
                '<tr><th style="text-align:right;font-weight:400;font-size:14px;">审批者：</th><td style="text-align:left;"><select>';
        for(var i in items) div += '<option value="'+items[i].id+'">'+ D.ifempty(items[i].approver_id_name, items[i].approver_id_account) +'</option>';
        div += '</option></td></tr></table></div>';

        top.layer.open({
            type: 1,
            title: '选择信息审批者',
            shadeClose: false,
            shade: [0.8, '#767676'],
            area: ['400px', '275px'],
            content: div,
            btn: ['确定', '取消'],
            yes: function(index, layero){ // 取抄表数据赋值到表单
                var approval_id = top.$('.approval-selecter select').val(),
                    f = $('form.edit');
                if(!f.length) f = $('form');
                wuuye.hidden('approval_id_approval_process', approval_id, f);
                top.layer.close(index);
                window.setTimeout(function(){callback();}, 200);
            }
        });
    },

    // 审批表单接入草稿支持
    formapproval : function(form, pwuuye){
        var btnsubmit = form.find('.btn-hidden');
        if(!wuuye.c.istoper) btnsubmit.remove(); // 仅在顶级窗口显示提交按钮，主用作调试
        if(!wuuye.c.is_approval) return; // 如果非需审批表单, 则不继续执行
        if(wuuye.c.istoper){
            $('<input type="button" value="保存" />').insertBefore(btnsubmit).bind('click', function(){
                wuuye.hidden(wuuye.c.elem_draft, 1, form);
                btnsubmit.trigger('click');
            });
        }else{
            if(!/is_approval/.test(location.hash)) window.setTimeout(function(){
                var wname = form.attr(wuuye.names.win);
                pwuuye.winbtn(wname, 'idsave', '保存并提交');
                var btn = pwuuye.winbtnn(wname, '.onlysave', {html : '<a class="onlysave" data-options="iconCls:\''+wuuye.names.iconsave+'\'">'+wuuye.names.textsave+'</a>'});
                btn.linkbutton({onClick : function(){
                    wuuye.hidden(wuuye.c.elem_draft, 1, form);
                    pwuuye.winbtnn(wname, '#'+wuuye.names.idsave).trigger('click');
                }});
            }, 300);
        }
    },

    // 建删点,存储值
    hidden : function(vname, data, wrap){
        var elem;
        if(typeof vname === 'object'){
            elem = $(vname);
        }else{
            wrap = wrap || $('form.edit');
            elem = wrap.find('[name='+vname+']');
            if(!elem.length) elem = $('<input type="hidden" name="'+vname+'" />').appendTo(wrap);
        }
        if(data === null) return elem.remove();
        return data === undefined ? elem.val() : elem.val(data);
    },

    formsuccess : function(pwuuye, rs, wname, pwin){
        pwuuye.savecall(rs, wname);
        if(!rs) rs = {status:0, info:'未知错误！'};
        pwuuye.winctrlbtn(wname, 2); // 还原编辑窗口保存按钮
        if(!rs.status) return alert_msg_box.alert_msg(rs.info || rs.message, false, false, true); // 操作失败直接返回而不关闭编辑窗口什么的
        alert_msg_box.alert_msg(rs.info || rs.message || '操作成功！', true, false, true);
        if($.isFunc(window.CALLBACK_save_call)) CALLBACK_save_call(rs);
        if(window.drunk_jump) return parent.location.reload();
    },
    names : {
        win : 'wuuye-wname',
        btnhidden : 'btn-hidden',
        iconsave : 'icon-save',
        iconloading : 'icon-loading',
        textloading : '载入中...',
        textsave : '保存',
        idsave : 'wuuyeid_save',
        idclose : 'wuuyeid_close'
    },
    cache : {'tagsOpened' : []}
};

// 明细相关方法
var bills = {
    d : {},
    details_ids : [],
    winame : 'dwinwin',
    purchaseDetailsLoad : function(c, gp_id){
        bills.request('/index.php?s=/base/purchase_details_get-druson~1-gp_id~'+gp_id+'.html', function(data){if(!$.isArray(data)) data=new Array();bills.detailsBuild(c, data);});
    },
    entryDetailsLoad : function(c, bit, goods_name, eid, bid, hid){
        return bit === -1 ?
            bills.request('/index.php?s=/base/lading_details_get-druson~1-eid~'+eid+'-bid~'+bid+'-hid~'+hid+'-goods_name~'+goods_name+'.html', function(data){bills.detailsBuild(c, data);}) :
            bills.request('/index.php?s=/base/entry_details_get-druson~1-wid~'+goods_name+'-goods_name~'+bit+'.html', function(data){bills.detailsBuild(c, data);});
    },
    detailsBuild : function(c, data){
        if(typeof billsFields === undefined) return false;
        var tval, tr, td, bit;
        c.detailsTbody.empty();
        for(var i=0;i<data.length;i++){
            tr = $('<tr data-id="'+ D.int(data[i]['id'])+'">').appendTo(c.detailsTbody);
            for(var j in c.fields){
                bit = D.int(c.fields[j].bit);
                if(bit & 2){
                    tval = bills.detailsCtrlBuild(c, data[i], j);
                }else{
                    tval = data[i][j] === undefined ? '' : data[i][j];
                }
                td = $('<td>').append(tval);
                tr.append(td);
            }
        }
    },
    // 明细空间建立
    detailsCtrlBuild : function(c, rs, j){
        var cf = c.fields[j], // ctrl fields
            cec = cf.elems,  // ctrl elems config
            elems = $(), // make an array
            i = 0,
            cc, elem; // call config
        if(!$.isArray(cec)) cec = [{label:cf.label, entrycall:cf.entrycall}]; // 若配置非数组配置, 则强转为数组
        for(; i<cec.length; i++){
            elem = $('<input type="button" value="'+cec[i].label+'" />');
            if(!$.isFunction(cec[i].entrycall)){ // 如果未传入有效的回调函数, 则尝试将传入字符转函数
                cc = String(cec[i].entrycall);
                cec[i].entrycall = cc.substr(0, 2) === 'c:' ? c[cc.substr(2)] : window[cc];
            }
            if($.isFunction(cec[i].entrycall)) elem.bind('click', {c : c, rs : rs}, cec[i].entrycall); // 以配置和配参位属性回调函数
            elems = elems.add(elem);
        }
        return elems;
    },
    itemSave : function(c, data){
        if(!D.int(data.response)) return null;
        if(!$.isArray(c.details_ids) || c.details_ids.search(data.response) != -1) return;
        var idsElem = $('[name='+ c.nameids+']');
        c.details_ids.push(data.response);
        idsElem.val(c.details_ids.join(','));
    },
    pwinstate : function(c, state){
        if(!state){
            wuuye.winctrl(c.winame, 4);
            parent.wuuye.winctrlbtn(c.pwiname, 2);
        }else if(state == 1){
            parent.wuuye.winctrlbtn(c.pwiname, 1);
        }else{
            wuuye.winctrlbtn(c.winame, 2);
            parent.wuuye.winctrlbtn(c.pwiname, 2);
        }
    },
    cfieldremove : function(c){
        var cw = wuuye[bills.winame].find('iframe')[0].contentWindow,
            c$ = cw.jQuery,  iptname, iptval, tr;
        for(var i=1; i<arguments.length; i++){
            iptname = $.isArray(arguments[i]) ? arguments[i][0] : arguments[i];
            iptval = $.isArray(arguments[i]) && arguments[i].length > 1 ? arguments[i][1] : 0;
            iptnohide = $.isArray(arguments[i]) && arguments[i].length > 2 ? arguments[i][2] : 0;
            try{
                tr = c$('[name='+iptname+']').val(iptval).closest('tr');
            }catch(e){
                tr = c$(iptname);
            }
            if(!iptnohide) tr.hide();
        }
    },
    request : function(url, callback){
        $.ajax({
            url : url,
            dataType : 'json',
            success : callback
        });
    },
    detailsInit : function(c){
        var tr, th, idsval,
            elemDetails_ids = $('[name='+c.nameids+']');
        c.detailsThead = $('.'+ c.wrap+'>thead');
        c.detailsTbody = $('.'+c.wrap+'>tbody');
        tr = $('<tr>').appendTo(c.detailsThead);
        if(idsval = elemDetails_ids.val()) D.extend(c.details_ids, D.empty(idsval) ? [] : idsval.split(/,/g));
        for(var i in c.fields){
            th = $('<th>'+c.fields[i].label+'</th>');
            tr.append(th);
        }
        bills.detailsGet(c);
    },
    // 取明细列表
    detailsGet : function(c){
        var elemIds = $('[name='+ c.nameids+']');
        ids = elemIds.val();
        if(D.empty(ids)) return;
        bills.request('/index.php?s=/base/details_get-druson~1-tab~'+ c.tab+'-ids~'+ids+'.html', function(data){
            bills.detailsBuild(c, data);
            if(c.tab == 'cost_expense_details'){ce_amountGet(c, data);}
        });
    },
    detailsDel : function(evt){ // 删除审批步骤
        var c = evt.data.c,
            rs = evt.data.rs,
            url_del = rs.url_del;
        if(!confirm('您确定要删除该记录吗？')) return;
        if(!url_del) url_del = '/index.php/base/approval_process_del-'+rs.id+'.html';
        dmonitor.request(url_del, function(data){
            if(!$.isPlainObject(data)) data = {};
            if(!data.status) return alert('删除失败！');
            bills.detailsGet(c); // 重载明细列表
        });
    },
    // 初始化
    init : function(c){
        c.details_ids = [];
        if(!c.wrap) c.wrap = 'details-list2';
        if(!c.nameids) c.nameids = 'details_ids';
        if(c.fields) bills.detailsInit(c); // 明细展示初始化
        if(c.addtrigger && $.isFunction(c.addcall)) $(c.addtrigger).bind('click', {c : c}, c.addcall); // 事件绑定初始化
    }
};

// 审批轮训相关
var dmonitor = {
    cache : {approval:{}},
    winame : 'winwinwin',
    passname : 'passname',
    latertime: 180000,
    refreshtime:5000,
    approvalOne : function(id){ // 查看或操作一条审批记录
        dmonitor.request('/index.php/base/take_approvaling-'+id+'.html', function(data){dmonitor.approvalCall(data, 1);});
    },
    /**
     * @param data object
     * @param status int   { 1:列表页详情操作 }
     * @returns {*}
     */
    approvalCall : function(data, status){
        status = D.int(status);
        var title = '有新的待审批项',
            islistpage = status & 1,
            isusefuldata = $.isPlainObject(data);
        if(!isusefuldata || (dmonitor.neverPopupAgain(data.id) && !islistpage)){ // 如果非有效数据, 或者有设置了不再弹窗且非列表页操作
            if(!isusefuldata && islistpage) return false; // 如果非有效数据且是列表页, 则返回假不再请求;
            return dmonitor.approval(); // 否则如果是有效数据但有设置不再弹窗且非列表页, 则返回真继续请求
        }
//        if(!data.menu_view.popup_config) data.menu_view.popup_config = {};
//        var wid = dmonitor.winame +'_'+ data.id,
//            config = {
//                config:{width: 600,height: 400},
//                callback:function(){},
//                closecall:function(){ if(!islistpage) dmonitor.approval(); },
//                loadcall:function(){},
//                savecall:function(data, wname){},
//              buttons:[
//                    {id:'neverpopup', text:'不再弹出',iconCls:'icon-forbid',style:'float:left;',handler:function(){dmonitor.neverPopupAgain(data.id, 1);}},//记录不再提示id
//                    {id:'appass', text:'通过',iconCls:'icon-ok',handler:function(){dmonitor.approvalPass(wid);}},
//                    {id:'apreject', text:'驳回',iconCls:'icon-no',handler:function(){dmonitor.approvalReject(wid);}}
//                ]
//     };
        if(islistpage){ // 如果是列表页, 则进行特殊处理
            title = '详情';
            config.buttons.splice(0, 1); // 干掉不再弹出按钮
            delete config.closecall; // 干掉关闭回调
       }
        if(D.int(data.status) & 5) config.buttons = [{text:'确定', iconCls:'icon-ok', handler:function(){wuuye.winctrlbtn(wid, 4);}}]; // 如果已处理，则仅显示确定按钮
    //    wuuye.window(data.url_view + '#is_approval', title, config, wid);
        dmonitor.approvalTopic(data,data.id);
        if(islistpage) return false; // 如果是列表页, 则返回假不再请求;
    },  
    approval : function(){
        var ids_not = dmonitor.neverPopupAgain(0, 2), //取不再提示id
            urlPart = D.empty(ids_not) ? '' : '-ids_not~' + ids_not.join(',');
        var iffirst = D.cookie('first');
        if(D.empty(iffirst)){
            dmonitor.request('/index.php/base/take_approvaling.html', dmonitor.handle);
            D.cookie('first','exit');
        }
        dmonitor.delay('/index.php/base/take_approvaling' +urlPart+ '.html', dmonitor.handle);
    },
    // iframe弹窗扩展同级主题组件
    approvalTopic : function(data, wid){
        dmonitor.cache.approval.id = data.id;
//        var component = $('<table class="edit">' +
//            '<tr><th>待审批项：</th><td>'+data.approval_id_name+'</td></tr>' +
//            '<tr><th>审批步骤：</th><td>'+data.approval_process_id_name+'</td></tr>' + dmonitor.approvalStatus(data) +
//            '<tr><th colspan="2" style="text-align:left;padding-left:44px;">待审内容：</th></tr>' +
//            '</table>'),
//            
//        //    popupWin = wuuye[wid || dmonitor.winame], // 取弹窗
//            pwHeight = popupWin.height(),
        var souce = D.cookie('apo');
        var time = new Date().getTime();
        if(!D.empty(souce)){
            var j = 0;
            var ids = [] ;
            var ta = $.parseJSON(souce);
            for(;j<ta.length;j++){
                ids[j] = ta[j].id;
            }
        }
        var id = data.id;
        if($.inArray(id,ids)>-1){
            var index = $.inArray(id,ids);
            if(id = data.id){
                if(time - ta[index].addtime < dmonitor.latertime){
                    return false;
                }
            }
        }
        var lay = $('.layui-layer');
        if(lay.length > 0)return false;

     //   if(!D.empty(data.messages) || !D.empty(data.task)) return false;
         layer.open({
        	  skin: 'new-btn-style',
        	  title:'<a style="font-weight:bold;">待我审批</a> ',
        	  type: 2,
        	  area: ['750px', '410px'],
        	  fix: false, //不固定
        	  maxmin: true,
        	  content: 'approval_by_me_view-'+data.id+'.html',
        	  btn: ['稍后提醒'],
        	  yes: function(index, layero){ //稍后提醒
                  dmonitor.laterPopuids(data.id,'apo');
                  layer.closeAll();
        	  }
        	});
        $('.layui-layer-close').click(function(){
            dmonitor.neverPopupAgain(data.id, 1);
        })
//        cHeight; // 主题组件尺寸
//        component.prependTo(popupWin);
//        cHeight = component.height();
//        popupWin.find('iframe:first').height(pwHeight - cHeight);
    },
    approvalStatus : function(data){
        var trs = [];
        if(!D.empty(data.statuses)) trs.push('<tr><th>当前状态：</th><td>'+data.statuses+'</td></tr>');
        if(!D.empty(data.memo_pre)){
            trs.push('<tr><th>来自：</th><td>'+data.approval_process_id_name_pre+'</td></tr>');
            trs.push('<tr><th>原因：</th><td>'+data.memo_pre+'</td></tr>');
        }
        return trs.join('');
    },
//    approvalPass : function(wid){ // 审批通过
//        wuuye.window('/index.php/base/approval_control_edit-'+dmonitor.cache.approval.id+'-1.html', "审批备注：", {
//            config:{width:400, height:250},
//            callback:function(){},
//            closecall:function(){},
//            loadcall:function(){},
//            savecall:function(data, wname){wuuye.winctrl(wid, 4);}
//        }, dmonitor.passname);
//    },
//    approvalReject : function(wid){ // 审批驳回
//        wuuye.window('/index.php/base/approval_control_edit-'+dmonitor.cache.approval.id+'.html', "驳回备注：", {
//            config:{width:400, height:250},
//            callback:function(){},
//            closecall:function(){},
//            loadcall:function(){},
//            savecall:function(data, wname){wuuye.winctrl(wid, 4);}
//        }, dmonitor.passname);
//    },
    neverPopupAgain : function(wid, bit){ // 不再弹窗
         _wid = wid;
        var key = 'appPPO';
        if(!bit){ // 是否有记录不再弹窗属性
            return D.cookied(wid, 0, key);
        }else if(bit & 2){ // 取不再弹出的项目记录值
            var neverPopIds = D.cookied(_wid, -1, key);
            if(!$.isArray(neverPopIds)) neverPopIds = [];
            for(var i=neverPopIds.length-1; i>=0; i--) if(neverPopIds[i] === '') neverPopIds.splice(0, 1);
            return neverPopIds;
        }
        if(!confirm('设置不再弹窗口该类型项目弹窗仅在重开浏览器后才会自动弹出！\n当然，您也可以到审批管理栏目去手动审批。\n\n是否继续？')) return;
        D.cookied(_wid, null, key);
   //     wuuye[dmonitor.winame +'_'+ wid].window('close');
        top.layer.closeAll();
        dmonitor.approval();//关闭后再尝试拉取最新消息
    },
    laterPopuids:function(wid,key,bit){
        //存数组
         var arr = D.cookie(key);
         if(arr == 'undefined'|| D.empty(arr)){
            var narr = [];
            var larr = {};
            var now = new Date().getTime();
            larr['id'] = wid;
            larr['addtime'] = now;
            narr.push(larr);
            var jso = D.dump(narr);
            D.cookie(key,jso);
         }else{
             var  lnarr = $.parseJSON(arr);
             var i = 0;
             var larr = {};
             var now = new Date().getTime();
             for(;i<lnarr.length;i++){
              if(wid == lnarr[i].id){
                lnarr.splice(i,1);
              }
             }
             larr['id'] = wid;
             larr['addtime'] = now;
             if(!D.empty(larr))lnarr.push(larr);
             var jso = D.dump(lnarr);
             D.cookie(key,jso);
         }
    },
    delay : function(url, callback){
        window.setTimeout(function(){
            dmonitor.request(url, callback);
        }, dmonitor.refreshtime);//120000
    },
    request : function(url, callback){
        $.ajax({
            url : url,
            dataType : 'json',
            success : callback
        });
    },
    //计划任务，信息改变状态操作
    laterState:function(id,key,jump){
        var url = '/index.php/base/tips_change_state.html';
        $.ajax({
          url : url,
          dateType: 'json',
          data:{id:id,key:key},
          success:function(){
          if(!D.empty(jump))location.href= jump;
          }
        });

    },
    // 处理定时器所取信息
    handle : function(data){
        if(!$.isPlainObject(data)) return dmonitor.approval();
        if(data.appro){
            dmonitor.approvalCall(data.appro);
        }
        if(data.messages){ // todo 暂时区分处理消息通知与审批通知
        	dmonitor.messagetips(data);
            dmonitor.approval();
        }
        if(data.task){
           dmonitor.tasktips(data);
            dmonitor.approval();
        }


    },
    messagetips:function(data){//2016-7-16版消息提醒(理想状态是消息和任务提醒一起)
        if(D.empty(data)) return false;
        var souce = D.cookie('msg');
        var time = new Date().getTime();
        if(!D.empty(souce)){
            var j = 0;
            var ids = [] ;
            var ta = $.parseJSON(souce);
            for(;j<ta.length;j++){
                ids[j] = ta[j].id;
            }
        }
        var i = 0;
        var win = $('.window').is(":visible"); //显示true
        if(win == true) return false;
        for(; i<data.messages.length; i++){
            var id = data.messages[i].id;
            if($.inArray(id,ids)>-1){
                var index = $.inArray(id,ids);
                if(id = ids[index]){
                    if(time - ta[index].addtime < dmonitor.latertime){
                        return false;
                    }
                }
            }

         var mess =    $e.messager.show({
                title:'新消息('+data.messages[i].title+')，请注意查收',
                height:'150',
                msg:data.messages[i].content+'<br/><a href="javascript:void(0)" style="color:#2D817D;float:left;margin-top:50px;" onclick="later(this, '+id+',\'msg\')">稍后提醒</a>',
                showType:'show',
                timeout:0
            });
            $('.messager-body').find('a:first').bind('click',function(){
                dmonitor.laterState(id,'msg',$(this).attr('href'));
                return false;
            })
            var $this = mess.prev();
            $this.find('a').attr('id',id);
            $this.find('a').unbind().bind('click',function(){
                 var mes_id = $(this).attr('id');
                 var war = $(this).parent().parent();
                 dmonitor.laterState(mes_id,'msg','');
                 $e(war).next().window('close');
            });
        }

    },
    tasktips:function(data){ //计划提醒
        if(D.empty(data)) return false;
        var souce = D.cookie('task');
        var time = new Date().getTime();
        if(!D.empty(souce)){
            var j = 0;
            var ids = [] ;
            var ta = $.parseJSON(souce);
            for(;j<ta.length;j++){
                ids[j] = ta[j].id;
            }
        }
        var i = 0;
        var win = $('.window').is(":visible"); //显示true
        if(win == true) return false;
        for(; i<data.task.length; i++){
            var id = data.task[i].id;
            if($.inArray(id,ids)>-1){
                var index = $.inArray(id,ids);
                if(id = ids[index]){
                    if(time - ta[index].addtime < dmonitor.latertime){
                        return false;
                    }
                }
            }
            var task = $e.messager.show({
                title:'到期计划提醒，请注意查看',
                height:'150',
                msg:'<a href="javascript:void(0)" style="color:#000" class="insead" url="'+id+'" onclick="dmonitor.laterState('+id+',\'task\',\'/index.php/base/task.html\')">'+data.task[i].memo+'</a><br/><a href="javascript:void(0);" class="later" style="color:#2D817D;float:left;margin-top:50px;"  onclick="later(this, '+id+',\'task\')">稍后提醒</a>',
                showType:'show',
                timeout:0
            });

            var $this = task.prev();
            $this.find('a').attr('id',id);
            $this.find('a').unbind().bind('click',function(){
                var mes_id = $(this).attr('id');
                var war = $(this).parent().parent();
                dmonitor.laterState(mes_id,'task','');
                $e(war).next().window('close');
            });
        }

    },
    // 处理信息队列供弹出
    messages : function(data){
        if(D.empty(data.messages)) return false;
        var i = 0;
        for(; i<data.messages.length; i++) dmonitor.messager(data.messages[i]);
        dmonitor.messageEvent();
    },
    // 取消息内容呗
    messager : function(rs){
        var html = '<div class="wuuye-message" data-id="'+rs.id+'" data-tabname="'+rs.list_menu_id_name+'">'+
            '<div class="wm-content">'+rs.content+
            '<div class="wm-time">'+D.date('Y-m-d H:i:s', rs.addtime)+'</div>'+ '</div>'+
            '<div class="wm-control">'+'</div></div>';
        dmonitor.traytip(html, rs.cid_name);
    },
    messageEvent : function(){
        var wrap = $('div.wuuye-message:not([data-binded])').attr('data-binded', 1),
            controls = wrap.find('a.control'),
            getid = function(elem, field){return elem.closest('.wuuye-message').attr(field || 'data-id');};
        controls.bind('click', function(){
            var elem = $e(this),
                elemwin = elem.closest('.messager-body');
            wuuye.handles[elem.attr('data-method')](getid(elem));
            elemwin.window('close');
            return false;
        });

        // 以下部分是新版通知通用设计方法
        wrap.find('a[data-tabwin]').bind('click', function(){
            var elem = $e(this),
                elemwin = elem.closest('.messager-body');
            eg.ctrlTab({"title":getid(elem, 'data-tabname'),"status":16,"urlmode":elem.attr('href')}); // 打开待处理的东西呗
            elemwin.window('close');
            return false;
        });
    },
    traytip : function(content, title){
        title = title || '通知提醒';
        return $e.messager.show({ title:title, msg:content, showType:'slide',timeout:0, width:320, height:'auto',
            style:{left:'', right:24, top:'', bottom:-document.body.scrollTop-document.documentElement.scrollTop} });
    }
};

$e(function(){
    wuuye.init();
    wuuye.formevent();
    eg.init();
});

function searchCall(url){
    eg.gridload(0, url);
}



/**
 * 以下皆蛋疼扩展
 */

// 查看审批记录
function view_approval_log(c, ids){
    if(!$.isArray(ids) || ids.length !== 1) return alert('仅支持同时查看一条审批记录！');
    return dmonitor.approvalOne(ids[0]);
}

//报销单的金额
function ce_amountGet(c,data){
    var temp = 0 ,elemtd = $('td.ce_amount');
    $.each(data,function(i,n){
        if($.isNumeric(n.amount)){
            temp += Number(n.amount);
            //console.log(n.amount,temp);
        }
    });
   
    elemtd.html(temp); 
}

function later(obj, wid,key){
   dmonitor.laterPopuids(wid,key, 1);
    $e(obj).closest('.messager-body').window('close');
}